package com.augmentum.login.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import com.augmentum.login.Constants;
import com.augmentum.login.exception.DBException;

public class DBUtil {

    public static final Connection getConnection() {

        Connection con = null;

        try {
            Class.forName(Prop.get(Constants.JDBC_DRIVER));
            con = DriverManager.getConnection(Prop.get(Constants.JDBC_URL), Prop.get(Constants.JDBC_USER), Prop.get(Constants.JDBC_PASSWORD));
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            throw new DBException();
        } catch (SQLException e) {
            e.printStackTrace();
            throw new DBException();
        }
        return con;
    }

    public static final void closeDBConnection(ResultSet rst, Statement stmt, Connection con) {
        if (rst != null) {
            try {
                rst.close();
            } catch (SQLException e) {
                e.printStackTrace();
                throw new DBException();
            }
        }
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
                throw new DBException();
            }
        }
        if (con != null) {
            try {
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
                throw new DBException();
            }
        }
    }

    public static void setAutoCommit(Connection conn, boolean autoCommit) {
        try {
            conn.setAutoCommit(autoCommit);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new DBException();
        }

    }

    public static void commit(Connection conn) {
        try {
            conn.commit();
        } catch (SQLException e) {
            e.printStackTrace();
            throw new DBException();
        }

    }

    public static void rollback(Connection conn) {
        try {
            conn.rollback();
        } catch (SQLException e) {
            e.printStackTrace();
            throw new DBException();
        }
    }
}
